#!/usr/bin/python
import os,sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import time
import threading
import re
from  xapi_get_all_host import *
from com.host_option import get_hostinfo
from utils.mode_logger import log
logger = log()
logger.info("----upate starting---------")

         
class ThreadDemo(threading.Thread):
    def __init__(self,host_ip,password):
        threading.Thread.__init__(self)
        self.host_ip=host_ip
        self.password=password
        #self.start()
        
    def run(self):
        update_ga(self.host_ip,self.password)
       
            
    def stop(self):
        self.thread_stop = True
        
def update_ga(host_ip,pwd):
    #from  xapi_vm_param_value import *
    try:
        test=get_vm_list(host_ip,pwd)
    except Exception,e:
        logger.criticl(e)
        break
    for s in test:
        for i in range(len(s)):
            vm_name=test[i]['name']
            vm_ipaddress=test[i]['ipaddress']
            cpu_used=[]
            global cpu_value
            cpu_value=0    
            sp=vm_ipaddress + ":" + vm_name.lower()
            if test[i]['value'].keys() == []:
                logger.criticl("can't get date from xenserver ,check local time")
            for pa in test[i]['value'].keys():
                get_values=test[i]['value'].get(pa)
                gangliaMetric=""
                if str(pa)== 'memory_target':
                    get_values=float(get_values)/1024/1024-(float(test[i]['value'].get('memory_internal_free'))/1024)
                    gangliaMetric = "/usr/bin/gmetric --name='Memmory Used' --spoof=" + sp + " --value="+str(get_values)+" --type=double --units=MB"
                elif re.search('cpu',str(pa)):
                    cpu_used.append(test[i]['value'].get(pa))
                elif str(pa) == ('vbd_xvda_write'):
                    gangliaMetric = "/usr/bin/gmetric --name=Disk_write --spoof=" + sp + " --value="+str(get_values)+" --type=double --units=seconds"
                elif str(pa) == ('vbd_xvda_read'):
                    gangliaMetric = "/usr/bin/gmetric --name=Disk_read --spoof=" + sp + " --value="+str(get_values)+" --type=float --units=bps"
                elif str(pa) == ('vif_0_tx'):
                    gangliaMetric = "/usr/bin/gmetric --name='Network Out' --spoof=" + sp + " --value="+str(get_values)+" --type=float --units=bps"
                elif str(pa) == ('vif_0_rx'):
                    gangliaMetric = "/usr/bin/gmetric --name='Network In'  --spoof=" + sp + " --value="+str(get_values)+" --type=float --units=bps"
                if gangliaMetric != "":
                    print gangliaMetric
                    res=os.system(gangliaMetric)
                for v in cpu_used:
                    cpu_value+=float(v)
                    if cpu_value == 0:
                        print ""
                    else:
                        cpuMetric = "/usr/bin/gmetric --name='AVG Cpu Used'" + " --spoof=" + sp + " --value="+str(cpu_value/(len(cpu_used))*100)+" --type=float --units=pecent"
                    	print cpuMetric
                        res=os.system(cpuMetric)
                    #   print res
            time.sleep(5) 

def main():
    while 1:
        try:
            host_list=get_hostinfo()
        except Exception,e:
            logger.criticl(e)
        s=3
        t=0
        for i in range(len(host_list)):
            sou=host_list[t:s]
            print sou
            t+=3
            s+=3
            for th in sou:
                host_ip=th['url']
                pwd=os.popen('/usr/bin/java -jar /root/cs-bs/xen_api/decrypt_password.jar '+th['password']).readlines()
                ths=ThreadDemo(host_ip,pwd[0])
                ths.setDaemon(True)
                logger.info(host_ip)
                ths.start()
            if t > len(host_list):
                break
        ths.join()
        print "%s" % (time.ctime(time.time()))

if __name__ == "__main__":
    main()
